package com.wzt.lianfirecontrol.fragment.home;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wzt.lianfirecontrol.App;
import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.activity.BaseActivity;
import com.wzt.lianfirecontrol.adapter.BaseRecyclerAdapter;
import com.wzt.lianfirecontrol.adapter.home.HomeDataAdapter;
import com.wzt.lianfirecontrol.adapter.home.HomeVideoListAdapter;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.home.HomeCountModel;
import com.wzt.lianfirecontrol.bean.recode.home.HomeJianCeModel;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.fragment.BaseFragment;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.GildeUtils;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.ScreenUtils;
import com.wzt.lianfirecontrol.utils.SpUtils;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.wzt.lianfirecontrol.utils.TypefaceUtil;
import com.wzt.lianfirecontrol.utils.Utils;
import com.wzt.lianfirecontrol.view.InitView;
import com.wzt.lianfirecontrol.view.SuperSwipeRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

public class HomeFragment extends BaseFragment implements SuperSwipeRefreshLayout.OnSwipeRefreshListener {
    private BaseActivity activity;
    private View itemContentView;
    private Bundle bundle;

    private SuperSwipeRefreshLayout swipe_container;

    /**
     * 列表头部图片
     */
    private ImageView iv_home_list_head;
    /**
     * 报警信息列表
     */
    private LinearLayout ll_item_hj;
    private TextView tv_hj_size;
    private LinearLayout ll_item_yj;
    private TextView tv_yj_size;
    private LinearLayout ll_item_gz;
    private TextView tv_gz_size;
    private LinearLayout ll_item_jg;
    private TextView tv_jg_size;
    /**
     * 消防通道占位图
     */
    private RelativeLayout rl_xiaofang_location;
    private TextView tv_xiaofang_location;
    private TextView tv_xiaofang_location_num;

    private RecyclerView rlv_list;
    private HomeDataAdapter homeDataAdapter;
    private LinearLayoutManager llm_home_list;

    private RecyclerView rlv_video_list;
    private HomeVideoListAdapter videoDataAdapter;
    private LinearLayoutManager llm_video_list;

    private View include_no_data;
    private View include_no_net;
    private View include_progress_bar;

    private final int HOME_LIST_REQUEST_WHAT = 0;
    private final int HOME_IMG_REQUEST_WHAT = 1;
    private final int HOME_COUNT_REQUEST_WHAT = 2;

    private boolean isFirstLoad = true;

    private String currentCompanyId = "";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView){
            bundle = getArguments();
            activity = getMyActivity();
            itemContentView = inflater.inflate(R.layout.f_home, container, false);
            currentCompanyId = UserInfoModel.getCompandId(activity);
            initView();
            initHttpHelper();
            initHomeImgHttpHelper();
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {
        swipe_container = itemContentView.findViewById(R.id.swipe_container);
        swipe_container.setOnSwipeRefreshListener(this);
        InitView.instance().initSuperSwipeLayout(swipe_container);

        initListView();
        initListHead();

        include_progress_bar = itemContentView.findViewById(R.id.include_progress_bar);
        InitView.instance().initProgressBar(activity, include_progress_bar);

        include_no_data = itemContentView.findViewById(R.id.include_no_data);

        include_no_net = itemContentView.findViewById(R.id.include_no_net);
        include_no_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateData();
            }
        });
    }

    @Override
    public void onSwipeRefresh() {
        activity.isRefreshing = true;
        swipe_container.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipe_container.setRefreshing(false);
                activity.isRefreshing = false;
                updateData();
            }
        }, 2000);
    }

    @Override
    public void updateData() {
        super.updateData();
        initHttpHelper();
        initHomeImgHttpHelper();
        initHomeCountHttpHelper();
    }

    @Override
    public void onPushDistanceMoreAction(int distance) {}

    @Override
    public void onPullEnableMoreAction(boolean enable) {}

    private void initListView() {
        rlv_list = itemContentView.findViewById(R.id.rlv_list);
        llm_home_list = new GridLayoutManager(activity, 2);
        llm_home_list.setOrientation(LinearLayoutManager.VERTICAL);
        rlv_list.setLayoutManager(llm_home_list);
        homeDataAdapter = new HomeDataAdapter(activity);
        rlv_list.setAdapter(homeDataAdapter);

        rlv_video_list = itemContentView.findViewById(R.id.rlv_video_list);
        llm_video_list = new GridLayoutManager(activity, 1);
        llm_video_list.setOrientation(LinearLayoutManager.VERTICAL);
        rlv_video_list.setLayoutManager(llm_video_list);
        videoDataAdapter = new HomeVideoListAdapter(activity);
        rlv_video_list.setAdapter(videoDataAdapter);
        videoDataAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<HomeJianCeModel>() {
            @Override
            public void onItemClick(View v, int position, HomeJianCeModel data) {
                // 跳转到“视频监控”页面
                HashMap<String, String> url_params = new HashMap<>();
                url_params.put(ConstData.SHOWTYPPE, ConstData.JIANKONGBUILDLIST);
                activity.setClickAction(ConstData.SHOWFRAG, ConstData.JIANKONGBUILDLIST, "视频监控", url_params);

            }
        });
        List<HomeJianCeModel> homeJianCeModels = new ArrayList<>();
        HomeJianCeModel homeJianCeModel = new HomeJianCeModel();
        homeJianCeModel.setSysName("视频监控");
        homeJianCeModel.setLogoImgRes(R.mipmap.icon_home_video);
        homeJianCeModels.add(homeJianCeModel);
        videoDataAdapter.addDatas(homeJianCeModels);

    }

    private void initListHead() {
        iv_home_list_head = itemContentView.findViewById(R.id.iv_home_list_head);
        ViewGroup.LayoutParams headImgLayoutParams = iv_home_list_head.getLayoutParams();
        headImgLayoutParams.height = (int) ((ScreenUtils.getScreenWidth(activity) - Utils.dip2px(activity, 40)) / 2f);

        iv_home_list_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        TypefaceUtil tfUtil = new TypefaceUtil(activity,"fonts/DINCond-Regular_0.otf");
        ll_item_hj = itemContentView.findViewById(R.id.ll_item_hj);
        tv_hj_size = itemContentView.findViewById(R.id.tv_hj_size);
        ll_item_yj = itemContentView.findViewById(R.id.ll_item_yj);
        tv_yj_size = itemContentView.findViewById(R.id.tv_yj_size);
        ll_item_gz = itemContentView.findViewById(R.id.ll_item_gz);
        tv_gz_size = itemContentView.findViewById(R.id.tv_gz_size);
        ll_item_jg = itemContentView.findViewById(R.id.ll_item_jg);
        tv_jg_size = itemContentView.findViewById(R.id.tv_jg_size);
        tfUtil.setTypeface(tv_hj_size,true);
        tfUtil.setTypeface(tv_yj_size,true);
        tfUtil.setTypeface(tv_gz_size,true);
        tfUtil.setTypeface(tv_jg_size,true);
        // 火警 1报警 2故障 4监管 98预警 6 屏蔽
        ll_item_hj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到火警界面
                HashMap<String, String> url_params = new HashMap<>();
                url_params.put("runStatus", ConstData.HUOJING_STATUS);
                url_params.put(ConstData.SHOWTYPPE, ConstData.HOME_BAOJING_DEVICE_LIST);
                activity.setClickAction(ConstData.SHOWFRAG, ConstData.INFOLIST, "火警", url_params);
                SpUtils.putString(App.context, "runStatus", "1");
            }
        });
        // 预警
        ll_item_yj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到预警界面
                HashMap<String, String> url_params = new HashMap<>();
                url_params.put("runStatus", ConstData.YUJING_STATUS);
                url_params.put(ConstData.SHOWTYPPE, ConstData.HOME_BAOJING_DEVICE_LIST);
                activity.setClickAction(ConstData.SHOWFRAG, ConstData.INFOLIST, "预警", url_params);
                SpUtils.putString(App.context, "runStatus", "98");
            }
        });
        // 故障
        ll_item_gz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到故障界面
                HashMap<String, String> url_params = new HashMap<>();
                activity.setClickAction(ConstData.SHOWFRAG, ConstData.BARTITLE, "", url_params);
                SpUtils.putString(App.context, "runStatus", "2");
            }
        });
        // 监管
        ll_item_jg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到监管页面
                HashMap<String, String> url_params = new HashMap<>();
                url_params.put("runStatus", Utils.changeStrToStatusId("监管"));
                url_params.put(ConstData.SHOWTYPPE, ConstData.HOME_BAOJING_DEVICE_LIST);
                activity.setClickAction(ConstData.SHOWFRAG, ConstData.INFOLIST, "监管", url_params);
                SpUtils.putString(App.context, "runStatus", "4");
            }
        });


        rl_xiaofang_location = itemContentView.findViewById(R.id.rl_xiaofang_location);

        TypefaceUtil xiaofangTfUtil = new TypefaceUtil(activity, "fonts/MStiffHeiPRC-UltraBold.ttf");
        tv_xiaofang_location = itemContentView.findViewById(R.id.tv_xiaofang_location);
        xiaofangTfUtil.setTypeface(tv_xiaofang_location, false);
        tv_xiaofang_location_num = itemContentView.findViewById(R.id.tv_xiaofang_location_num);
        rl_xiaofang_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activity.setClickAction(ConstData.SHOWFRAG, ConstData.XFTD, "消防通道占用", null);
            }
        });
    }

    /**
     * 获取首页列表
     */
    private void initHttpHelper() {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        include_progress_bar.setVisibility(View.VISIBLE);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put(ConstData.COMPANYID, UserInfoModel.getCompandId(activity));

        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        HttpHelper homeListHttpHelper = new HomeListHttpHelper(activity, Url.HOME_URL, HOME_LIST_REQUEST_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new HomeParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }

    /**
     * 获取首页图片
     */
    private void initHomeImgHttpHelper() {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        include_progress_bar.setVisibility(View.VISIBLE);
        HashMap<String, Object> hashMap = new HashMap<>();
        // 公司id
        hashMap.put("id", UserInfoModel.getCompandId(activity));
        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        HttpHelper homeListHttpHelper = new HomeListHttpHelper(activity, Url.HOME_IMAGE_URL, HOME_IMG_REQUEST_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new HomeParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }

    /**
     * 获取首页报警信息
     */
    private void initHomeCountHttpHelper() {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put(ConstData.COMPANYID, UserInfoModel.getCompandId(activity));

        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        HttpHelper homeListHttpHelper = new HomeListHttpHelper(activity, Url.HOME_COUNT_URL, HOME_COUNT_REQUEST_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new HomeParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }

    private class HomeListHttpHelper extends HttpHelper{
        public HomeListHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

   protected class HomeParseJsonData extends ParseJsonData{

       public HomeParseJsonData() {
       }

       @Override
       public void analyzeResult(String dataStr, Bundle bundle, int what) {
            switch (what){
                case HOME_LIST_REQUEST_WHAT:
                    try {
                        LinkedList<HomeJianCeModel> models = (LinkedList<HomeJianCeModel>) JSONUtil.jsonArrayToBeanList(new JSONArray(dataStr), HomeJianCeModel.class);
                        if (null != models && models.size() > 0){
                            bundle.putSerializable("xfSystemInfo", models);
                        }
                        bundle.putBoolean(REQUEST_OK, true);

                    } catch (JSONException e) {
                        e.printStackTrace();
                        bundle.putBoolean(REQUEST_OK, false);
                        bundle.putString(ERROR_MSG, ANALYZE_ERROR_MSG);
                    }
                    break;
                case HOME_IMG_REQUEST_WHAT:
                    try {
                        if (StringUtils.isEmpty(dataStr) || "null".equals(dataStr)){
                            bundle.putString("img", "");
                        }else {
                            bundle.putString("img", dataStr);
                        }
                        bundle.putBoolean(REQUEST_OK, true);

                    } catch (Exception e) {
                        e.printStackTrace();
                        bundle.putBoolean(REQUEST_OK, false);
                        bundle.putString(ERROR_MSG, ANALYZE_ERROR_MSG);
                    }
                    break;
                case HOME_COUNT_REQUEST_WHAT:
                    try {
                        JSONObject jsonObject = new JSONObject(dataStr);
                        String homeCount = jsonObject.getString("homeCount");
                        HomeCountModel homeCountModel = JSONUtil.jsonObjectToBean(new JSONObject(homeCount), HomeCountModel.class);
                        bundle.putSerializable("homeCountModel", homeCountModel);
                        bundle.putBoolean(REQUEST_OK, true);
                    }catch (Exception e){
                        bundle.putBoolean(REQUEST_OK, false);
                        bundle.putString(ERROR_MSG, ANALYZE_ERROR_MSG);
                    }
                    break;
            }
       }
   }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
            //ToastUtils.showToast(activity, bundle.getString(ParseJsonData.ERROR_MSG));
            include_progress_bar.setVisibility(View.GONE);
            include_no_net.setVisibility(View.GONE);
            include_no_data.setVisibility(View.GONE);
            return;
        }
        switch (msg.what){
            case HOME_LIST_REQUEST_WHAT:
                include_progress_bar.setVisibility(View.GONE);
                setListData((LinkedList<HomeJianCeModel>)bundle.getSerializable("xfSystemInfo"));
                break;
            case HOME_IMG_REQUEST_WHAT:
                include_progress_bar.setVisibility(View.GONE);
                String img = bundle.getString("img");
                if (!StringUtils.isEmpty(img)){
                    GildeUtils.loadImage(activity, iv_home_list_head, img, R.mipmap.item_image);
                }else {
                    iv_home_list_head.setImageResource(R.mipmap.item_image);
                }
                break;
            case HOME_COUNT_REQUEST_WHAT:
                include_progress_bar.setVisibility(View.GONE);
                setBjInfo((HomeCountModel) bundle.getSerializable("homeCountModel"));
                break;
        }
    }

    /**
     * 设置列表头部报警信息列表
     * @param homeCountModel
     */
    private void setBjInfo(HomeCountModel homeCountModel) {
        tv_hj_size.setText(homeCountModel.getFireCount());
        tv_yj_size.setText(homeCountModel.getEarlyCount());
        tv_gz_size.setText(homeCountModel.getFaultCount());
        tv_jg_size.setText(homeCountModel.getSuperviseCount());
    }


    /**
     * 设置列表数据
     * @param listData
     */
    private void setListData(LinkedList<HomeJianCeModel> listData) {
        if (null == listData || listData.size() == 0){
            homeDataAdapter.clear();
            include_no_data.setVisibility(View.GONE);
            return;
        }
        include_no_data.setVisibility(View.GONE);
        homeDataAdapter.clear();
        homeDataAdapter.addDatas(listData);
        homeDataAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<HomeJianCeModel>() {
            @Override
            public void onItemClick(View v, int position, HomeJianCeModel data) {
                // 跳转到建筑物信息列表
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("showType", ConstData.LOCATIONLIST);
                hashMap.put("equSysId", data.getId());
                activity.setClickAction(ConstData.SHOWFRAG, ConstData.INFOLIST,
                        data.getSysName(), hashMap);
            }
        });
    }

    @Override
    public void skipToTop() {
        if (null != rlv_list && null != homeDataAdapter && homeDataAdapter.getItemCount() > 0){
            rlv_list.smoothScrollToPosition(0);
        }
    }

    @Override
    public boolean isRefreshing() {
        return swipe_container.isRefreshing();
    }

    @Override
    public void onResume() {
        super.onResume();
        initHomeCountHttpHelper();
        if (!isFirstLoad) {}
        isFirstLoad = false;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && !isFirstLoad){
            if (!currentCompanyId.equals(UserInfoModel.getCompandId(activity))){
                updateData();
            }else {
                initHomeCountHttpHelper();
            }
        }
    }


}
